package cn.top.fenci.ikutil;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.util.ResourceLoader;
import org.springframework.core.io.ClassPathResource;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;
import org.wltea.analyzer.dic.Dictionary;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.*;
import java.util.*;


/**
 * @Autor zhangjiawen
 * @Date: 2020/11/19 15:17
 */
public class IKTest2 {

    private static Dictionary singleton;
    private static ResourceLoader loader;
    static List<String> dictList = new ArrayList<String>();



    public static void main(String[] args) throws Exception {
        test();
        //updateFile("E:/dict.dic","777");


    }

    public static void test() throws IOException{
        String content = "我是一个好人，他是坏人";
        StringReader reader = new StringReader(content.trim());
        MyConfiguration cfg = new MyConfiguration();
        // 加载词库
        cfg.setUseSmart(true); // 设置智能分词
        Dictionary.initial(cfg);


        Dictionary dictionary = Dictionary.getSingleton();
        //List<String> disa = getWordList("dict/dict1.dic");
        List<String> ext = getWordList("dict/dict2.dic");
        System.out.println(ext);

       // dictionary.disableWords(disa);

        dictionary.addWords(ext); // 自动添加自定义词



// 创建分词对象 isMaxWordLength
        Analyzer anal = new IKAnalyzer(true);//true也标示最大词长
// 分词
        TokenStream ts = anal.tokenStream("", reader);

        ts.reset();
        CharTermAttribute term = ts.getAttribute(CharTermAttribute.class);
// 遍历分词数据
        String rc0 = "";
        while (ts.incrementToken()) {
// System.out.print(term.toString() + "     ");
            rc0 = rc0 + term.toString() + "|";
        }
        System.out.println(rc0);
    }

    /**
     * 读取字典
     * @param dict
     * @return
     */
    public static List<String> getWordList(String dict) {
        List<String> list = new ArrayList<>();
        InputStream is = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource(dict);
            //is = IKTest2.class.getResourceAsStream(dict);
            is =classPathResource.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"), 1024);
            String theWord = null;
            do {
                theWord = br.readLine();
                if (theWord != null && !"".equals(theWord.trim())) {
                    list.add(theWord);
                }
            } while (theWord != null);
        } catch (IOException ioe) {
            System.err.println("字典文件读取失败:"+dict);
            ioe.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return list;
    }






    /**
     * 传递键值对的Map，更新properties文件

     */
    public static void updateFile(String filePath, String word) throws Exception {
        //获取文件路径
        System.out.println("propertiesPath:" + filePath);
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            // 从输入流中读取属性列表（键和元素对）
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));

            if(!br.ready())
            {
                System.out.println("文件流暂时无法读取");
                return;
            }
            Set<String> set=new HashSet<>();
            String string;
            while((string=br.readLine())!=null)
            {
                //因为读取到的是int类型的，所以要强制类型转换

                //System.out.println(string);
                set.add(string.trim());

            }
            br.close();
            set.add(word);
            // 写入属性文件
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()){
                String next = iterator.next();
                bw.write(next);
                bw.newLine();
            }


            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Visit " + filePath + " for updating " + "" + " value error");
        } finally {
            try {
                br.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
